package com.gange.aspect;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gange.mapper.OperateLogMapper;
import com.gange.pojo.OperateLog;
import com.gange.utils.CurUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.logging.LogManager;

@Component
@Aspect
@Slf4j
@Order(3)
public class LogAspect {
    @Autowired
    private OperateLogMapper logMapper;
    @Pointcut("@annotation(com.gange.aspect.annotation.Log)")
    public void pc(){

    }

    @Around("pc()")
    public Object calTime(ProceedingJoinPoint joinPoint) throws Throwable {
        //操作人、操作时间、执行方法的全类名、执行方法名、方法运行时参数、返回值、方法执行时长
        Integer userId = CurUserInfo.getUserId();
        LocalDateTime curTime = LocalDateTime.now();
        long startTime = System.currentTimeMillis();
        //调用目标方法
        Object proceed = joinPoint.proceed();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        String argsStr = Arrays.toString(joinPoint.getArgs());
        long endTime = System.currentTimeMillis();
        long time = endTime - startTime;

        //讲一个java对象转换为对应的json串
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(proceed);
        OperateLog logger = new OperateLog(null,userId,curTime,className,methodName,argsStr,json,time);
        logMapper.insert(logger);
        return proceed;
    }
}
